<template>
  <p-card :bordered="false">

    <!-- 查询区域 -->
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <p-form
        layout="inline"
        @keyup.enter.native="searchQuery"
      >
        <p-row :gutter="24">
          <p-col :span="5">
            <p-form-item label="车间">
                <p-select
                option-filter-prop="children"
                :filter-option="filterOption"
                v-model="active.workroomname"
              >

                <p-select-option
                  @click="QueryData(value)"
                  :key="value.workroomno"
                  :value="value.workroomname"
                  v-for="value in userlist"
                >{{value.workroomname}}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :span="5">
            <p-form-item label="线体">
              <p-select placeholder="请选择" v-model="activeList.linename">
                <!-- 遍历下拉选择框选项 -->
                <p-select-option
                  @click="QueryList(item)"
                  v-for="item in list"
                  :value="item.linename"
                  :key="item.lineno"
                >{{item.linename}}</p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :span="5">
            <p-form-item label="选择日期">
              <p-date-picker
                v-model="startDate"
                format="YYYY-MM-DD"
                @change="changeDate"
               
              />
            </p-form-item>
          </p-col>
          <p-col :span="3">
            <span
              style="float: left;overflow: hidden;"
              class="table-page-search-submitButtons"
            >
              <p-button
                type="primary"
                @click="searchQuery"
                icon="search"
              >查询</p-button>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <p-button
        @click="handleAdd"
        type="primary"
      >开班检验</p-button>
      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      ></j-super-query>
    </div>

    <!-- 导入导出功能栏 -->
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <a @click="loadData()"> <p-icon type="sync" />刷新 </a>
        <span style="float: right">
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12" :key="index">
                        <p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a> <p-icon type="setting" />自定义列 </a>
          </p-popover>
        </span>
      </div>


    <!-- table区域-begin -->
    <div>
      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template
          slot="action"
          slot-scope="text, record"
        >
          <a
            v-if="record.status == '1'"
            @click="handleCheck(record)"
          >查询</a>
        </template>
      </p-table>
    </div>
    <!-- table区域-end -->

    <mesClassCheck-modal
      ref="modalForm"
      :EnhanceJS="EnhanceJS"
      @ok="modalFormOk"
    ></mesClassCheck-modal>
    <!-- 弹出窗 -->

    <!--详情-->
    <mesClassDetail-drawer
      ref="detailRef"
      :isShowAction="true"
    ></mesClassDetail-drawer>
  </p-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import { filterObj } from '@/utils/util';
import Vue from 'vue'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import ButtonExpHandler from '@/components/jeecgbiz/modules/ButtonExpHandler'
import { postAction, getAction, deleteAction, api } from '@/api/manage'
import FxCompontensModal from "@/components/jeecgbiz/FxCompontensModal"
import { ajaxGetDictItems } from '@/api/api'
import MesClassCheckModal from './modules/MesClassCheckModal'
import MesClassDetailDrawer from './modules/MesClassDetailDrawer'
import moment from 'moment'

//高级查询modal需要参数
const superQueryFieldList = [
  {
    value: 'orderNo',
    text: '检验单号',
    type: 'string'
  },
  {
    value: 'processbillno',
    text: '工序工单',
    type: 'string'
  },
  {
    value: 'productCode',
    text: '产品编码',
    type: 'string'
  },
  {
    value: 'productName',
    text: '产品名称',
    type: 'string'
  },
  {
    value: 'linename',
    text: '线体',
    type: 'string'
  },
  {
    value: 'status',
    text: '检验状态',
    type: 'select',
    dictCode: 'mes_class_test_status'
  },
  {
    value: 'startDate',
    text: '开班检验日期',
    type: 'Date'
  },
  {
    value: 'updateTime',
    text: '开班检验时间',
    type: 'Date'
  },
  {
    value: 'checkUid',
    text: '检验人员',
    type: 'string'
  },
]

export default {
  name: "MesClassCheck",
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery,
    FxCompontensModal,
    MesClassCheckModal,
    MesClassDetailDrawer
  },
  data () {
    return {
      // 线体列表
      userlist: [],
      active:[],
      list:[],
      Date:'',
      activeList:[],
      fieldList: superQueryFieldList,
      superQueryFlag: false,
      superQueryParams: '',
      description: '工站地址码信息管理页面',
      cgButtonLinkList: [],
      title: '',//存表名
      EnhanceJS: '',
      cgButtonList: [],
      groupTag: [],
      queryInfo: [],
      code: '',
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '检验单号',
          align: 'center',
          dataIndex: 'orderNo',
        },
        {
          title: '工序工单',
          align: 'center',
          dataIndex: 'processbillno',
        },
        {
          title: '产品编码',
          align: 'center',
          dataIndex: 'productCode',
        },
        {
          title: '产品类别',
          align: 'center',
          dataIndex: '',
        },
        {
          title: '工单类型',
          align: 'center',
          dataIndex: '',
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'productName',
        },
        {
          title: '线体',
          align: 'center',
          dataIndex: 'linename',
        },
        {
          title: '检验状态',
          align: 'center',
          dataIndex: 'status',
          customRender: (text) => {
            if (!text.toString()) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['status'], text + '')
            }
          },
        },
        {
          dataIndex: 'starttime',
          title: '计划开始时间',
          align: 'center',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return moment(text).format('YYYY-MM-DD')
            }
          }
        },
        {
          title: '开班检测日期',
          align: 'center',
          dataIndex: 'testDate',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: '检验人员',
          align: 'center',
          dataIndex: 'checkUid',
        },
        {
          title: '检验记录',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/mes-manufacture/mfClassTest/list',
        classList: '/mes-manufacture/mfClassTest/getFilter', // 班组下拉值
        //获取当前用户信息
        currentUserUid: "/mes-manpower/mesHrEmployeeinfo/currUser",
      },
      dictOptions: {
        status: []
      },
      lineList: [], // 线体
      classList: [], // 班组
      employeeinfo: '',
      startDate: ''
    }
  },
  computed: {
    tableScroll: function () {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 }
      }
    }
  },
  created () {
    this.getuserUidList()
    this.getConfig()
    this.getData()
    this.initColumns();
    // this.loadData()
  },

  methods: {
    moment,
    changeDate (val,str) {
      this.Date=str
      // this.startDate=moment(str,'YYYY-MM-DD')
    },
    getConfig () {
      ajaxGetDictItems('mes_class_test_status', null).then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'status', res.data)
        }
      })
    },
    handleAdd () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    getData () {
      this.employeeinfo = JSON.parse(localStorage.getItem('employeeinfo')) // 获取当前人员信息 
      if (this.employeeinfo) {
        this.getClass()
        this.lineList[0] = {
          value: this.employeeinfo.lineno,
          label: this.employeeinfo.linename
        }
      }
    },
    // 获取班组下拉框
    getClass () {
      getAction(this.url.classList, {
        lineno: this.employeeinfo.lineno,
        workroomno: this.employeeinfo.workroomno
      }).then(res => {
        if (res.code == 0) {
          this.classList = res.data || []
        }
      })
    },

    // 根据用户信息加载车间
    loadWorkroomno(data) {
      this.userlist = this.getWorkrooms(data);
      this.active = this.getWorkrooms(data)[0];
      this.linenoCode = this.getWorkrooms(data);
      this.list = this.active.lines;
      this.activeList = this.active.lines[0];
      this.EnhanceJS={
        ...this.active,
        ...this.activeList
      }
    },
    // 选择车间,拉取线体
    QueryData(data) {
      this.active = data;
      this.list = data.lines;
      this.activeList = data.lines[0];
    },
    QueryList(data){
      this.activeList=data
    },

    // 查询
    handleCheck (record) {
      console.log(record)
      this.$refs.detailRef.show(record)
    },
    initColumns () {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        })
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        })
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange (checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols;
    },

    //高级查询方法
    handleSuperQuery (arg) {
      if (!arg) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(arg)
      }
      this.loadData()
    },
    // 获取查询条件
    getQueryParams () {
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    initDictConfig () {
    },

    // 弹出窗组件
    showDemoModal () {
      this.$refs.modalCompon.modalShow();
    },

    //uid 用户
    getuserUidList() {
      getAction(this.url.currentUserUid, { sysCode: "mes" }).then((res) => {
        if (res.success) {
          // this.$message.success(res.msg);
          // this.userInfo = res.data;
          // this.selectData = res.data;
          this.loadWorkroomno(res.data);
          this.loadData();
        }
        if (res.code === 510) {
          this.$message.warning();
        }
      });
    },

    // 处理车间数据函数
    getWorkrooms(auth) {
      var dutyDtos = auth.dutyDtos;
      var workroomnos = new Array();
      for (var i = 0; i < dutyDtos.length; i++) {
        var temp = dutyDtos[i];
        var elment = this.getWorkroomItem(workroomnos, temp.workroomno);
        if (elment == null) {
          elment = {
            workroomno: temp.workroomno,
            workroomname: temp.workroomname,
            lines: new Array(),
          };
          workroomnos.push(elment);
        }
        var lineElement = {
          lineno: temp.lineno,
          linename: temp.linename,
          classno: temp.classno,
          classname: temp.classname,
        };
        elment.lines.push(lineElement);
      }
      return workroomnos;
    },
    // 处理车间数据函数
    getWorkroomItem(workroomnos, workroomno) {
      var result = null;
      for (var i = 0; i < workroomnos.length; i++) {
        var item = workroomnos[i];
        if (workroomno === item.workroomno) {
          result = item;
          break;
        }
      }
      return result;
    },
    // 加载表格数据
    loadData(arg) {
      if (!this.url || !this.url.list) {
        console.log('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      console.log(params)
        getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records
          this.ipagination.total = res.data.total
        }
        if (res.code === 510) {
          this.$message.warning(res.msg)
        }
        this.loading = false
      })
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      // var param = Object.assign(sqp,this.queryParam, this.isorter, this.filters)
      var param={}
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      param.limit = this.ipagination.pageSize
      param.lineno=this.activeList.lineno
      param.workroomno=this.active.workroomno
      param.startDate=this.Date
      return filterObj(param)
    },
     handleTableChange(a){
      this.ipagination=a
      this.loadData()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>